#include "recbox.h"
#include "ui_recbox.h"
#include "recboxitem.h"
#include <QJsonObject>
#include <QDebug>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox), row(1), col(4)
{
    ui->setupUi(this);
}

RecBox::~RecBox()
{
    delete ui;
}

// 初始化图片等资源和行数列数
void RecBox::InitRecBoxUi(QJsonArray data, int row)
{
    if (row == 2)
    {
        this->row = row;
        this->col = 8;
    }
    else
    {
       ui->recListDown->hide();
    }

    imageList = data;
    // 默认显示第0组
    currIndex = 0;
    count = imageList.size() / col;
    // 添加对应图片
    createRecBoxItem();
}

void RecBox::createRecBoxItem()
{
    // 先清除旧的元素
    QList<RecBoxItem*> recUpList = ui->recListUp->findChildren<RecBoxItem*>();
    for (auto e : recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;
    }
    QList<RecBoxItem*> recDownList = ui->recListDown->findChildren<RecBoxItem*>();
    for (auto e : recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;
    }
    // 创建RecBoxItem对象，并添加
    // 下面的补给col是8，需要判断条件往下边添加
    int index = 0;  // 用来判断是不是2行下面的元素
    for (int i = currIndex * col; i < col + currIndex * col; i++)
    {
        RecBoxItem* item = new RecBoxItem(this);

        // 设置图片和对应文本
        QJsonObject obj = imageList[i].toObject();
        item->setRecImage(obj.value("path").toString());
        item->setRecText(obj.value("text").toString());
        // 当2行时需要判断是不是第二行的图片，1行全部添加到上面
        if (row == 2 && index >= col / 2)
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        {
            ui->recListUpHLayout->addWidget(item);
        }

        index++;
    }
}

void RecBox::on_btUp_clicked()
{
    currIndex--;
    // 越界
    if (currIndex < 0)
    {
        currIndex = count - 1;
    }

    createRecBoxItem();
}

void RecBox::on_btDown_clicked()
{
    currIndex++;
    // 越界
    if (currIndex >= count)
    {
        currIndex = 0;
    }

    createRecBoxItem();
}
